package com.platform.module.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.platform.common.annotation.DataScope;
import com.platform.common.constant.UserConstants;
import com.platform.common.core.domain.Ztree;
import com.platform.common.core.text.Convert;
import com.platform.common.exception.BusinessException;
import com.platform.common.utils.DateUtils;
import com.platform.common.utils.StringUtils;
import com.platform.common.utils.redis.RedisUtil;
import com.platform.module.domain.*;
import com.platform.module.mapper.BaseValveDataMapper;
import com.platform.module.mapper.BaseValveTypeMapper;
import com.platform.module.mapper.LinkConcentratorValveMapper;
import com.platform.module.service.IBaseValveDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 阀门设备数据Service业务层处理
 * 
 * @author wangqi
 * @date 2020-07-13
 */
@Service
public class BaseValveDataServiceImpl extends ServiceImpl<BaseValveDataMapper,BaseValveData> implements IBaseValveDataService
{
    @Autowired
    private BaseValveDataMapper baseValveDataMapper;

    @Autowired
    private BaseValveTypeMapper baseValveTypeMapper;

    @Autowired
    private LinkConcentratorValveMapper linkConcentratorValveMapper;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 将采集器和热表关联存放到redis
     */
    @PostConstruct
    public void init() {
        List<BaseValveData> list = baseValveDataMapper.selectBaseValveDataList(new BaseValveData());
        for(BaseValveData valveData : list){
            redisUtil.hset("valveData", valveData.getValveId(), valveData);
        }
    }

    /**
     * 查询阀门设备数据列表
     * 
     * @param baseValveData 阀门设备数据
     * @return 阀门设备数据
     */
    @Override
    public List<BaseValveData> selectBaseValveDataList(BaseValveData baseValveData)
    {
        return baseValveDataMapper.selectBaseValveDataList(baseValveData);
    }

    /**
     * 新增阀门设备数据
     * 
     * @param baseValveData 阀门设备数据
     * @return 结果
     */
    @Override
    @Transactional
    public int insertBaseValveData(BaseValveData baseValveData)
    {
        saveLink(baseValveData);
        baseValveData.setCreateTime(DateUtils.getNowDate());
        //将热表数据保存到redis
        redisUtil.hset("valveData", baseValveData.getValveId(), baseValveData);
        return baseValveDataMapper.insert(baseValveData);
    }

    /**
     * 修改阀门设备数据
     * 
     * @param baseValveData 阀门设备数据
     * @return 结果
     */
    @Override
    @Transactional
    public int updateBaseValveData(BaseValveData baseValveData)
    {
        saveLink(baseValveData);
        baseValveData.setUpdateTime(DateUtils.getNowDate());
        //将热表数据保存到redis
        redisUtil.hset("valveData", baseValveData.getValveId(), baseValveData);
        return baseValveDataMapper.updateById(baseValveData);
    }

    /**
     * 保存阀门和采集器的对应关系
     * @param baseValveData
     */
    @Transactional
    void saveLink(BaseValveData baseValveData){
        if(baseValveData.getConcentratorId()!=null &&  !baseValveData.getConcentratorId().equals("")) {
            if(redisUtil.hHasKey("concentratorValve", baseValveData.getValveId())){
                String concentrarotId = redisUtil.hget("concentratorValve", baseValveData.getValveId()).toString();
                if(!concentrarotId.equals(baseValveData.getConcentratorId())) {
                    linkConcentratorValveMapper.delete(new QueryWrapper<LinkConcentratorValve>().eq("valve_id", baseValveData.getValveId()));
                    LinkConcentratorValve linkConcentratorValve = new LinkConcentratorValve();
                    linkConcentratorValve.setConcentratorId(baseValveData.getConcentratorId());
                    linkConcentratorValve.setValveId(baseValveData.getValveId());
                    linkConcentratorValveMapper.insert(linkConcentratorValve);
                }
            }else{
                LinkConcentratorValve linkConcentratorValve = new LinkConcentratorValve();
                linkConcentratorValve.setConcentratorId(baseValveData.getConcentratorId());
                linkConcentratorValve.setValveId(baseValveData.getValveId());
                linkConcentratorValveMapper.insert(linkConcentratorValve);
            }
            redisUtil.hset("concentratorValve", baseValveData.getValveId(), baseValveData.getConcentratorId());
        }
    }

    /**
     * 删除阀门设备数据对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteBaseValveDataByIds(String ids)
    {
        for(String id : Arrays.asList(Convert.toStrArray(ids))){
            redisUtil.hdel("valveData", id);
        }
        return baseValveDataMapper.deleteBatchIds(Arrays.asList(Convert.toStrArray(ids)));
    }

    /**
     * 导入阀门信息数据
     *
     * @param valveDataList 阀门信息数据
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    @Transactional
    public String importBaseValveData(List<BaseValveData> valveDataList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(valveDataList) || valveDataList.size() == 0)
        {
            throw new BusinessException("导入阀门信息数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (BaseValveData valveData : valveDataList)
        {
            try
            {
                //查询阀门类型
                QueryWrapper<BaseValveType> queryWrapper = new QueryWrapper<BaseValveType>();
                queryWrapper.eq("type_name",valveData.getTypeName());
                BaseValveType valveType = baseValveTypeMapper.selectOne(queryWrapper);
                if(valveType!=null){
                    valveData.setTypeId(valveType.getTypeId());
                }

                //查询阀门信息是否存在
                BaseValveData valve = baseValveDataMapper.selectById(valveData.getValveId());
                if (StringUtils.isNull(valve))
                {
                    valveData.setCreateBy(operName);
                    valveData.setCreateTime(DateUtils.getNowDate());
                    this.insertBaseValveData(valveData);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、阀门 " + valveData.getValveId() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    valveData.setUpdateBy(operName);
                    valveData.setUpdateTime(DateUtils.getNowDate());
                    this.updateBaseValveData(valveData);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、阀门 " + valveData.getValveId() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、阀门 " + valveData.getValveId() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、阀门 " + valveData.getValveId() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BusinessException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }


    /**
     * 根据条件分页查询已分配阀门列表
     *
     * @param valveData 阀门信息
     * @return 阀门信息集合信息
     */
    @Override

    public List<BaseValveData> selectAllocatedList(BaseValveData valveData)
    {
        return baseValveDataMapper.selectAllocatedList(valveData);
    }


    /**
     * 根据条件分页查询未分配阀门角色列表
     *
     * @param baseValveData 阀门信息
     * @return 阀门信息集合信息
     */
    @Override

    public List<BaseValveData> selectUnallocatedList(BaseValveData baseValveData)
    {
        return baseValveDataMapper.selectUnallocatedList(baseValveData);
    }

    /**
     * 校验阀门id是否唯一
     *
     * @param baseValveData 阀门信息
     * @return 结果
     */
    @Override
    public String checkValveDataCodeUnique(BaseValveData baseValveData)
    {
        String status = StringUtils.isNull(baseValveData.getStatus()) ? "" : baseValveData.getStatus();
        BaseValveData valveData = baseValveDataMapper.selectById(baseValveData.getValveId());
        if (StringUtils.isNotNull(valveData) && !baseValveData.getValveId().equals(status))
        {
            return UserConstants.VALVE_ID_NOT_UNIQUE;
        }
        return UserConstants.VALVE_ID_UNIQUE;
    }

    /**
     * 查询阀门树
     *
     * @return 所有阀门信息
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<Ztree> selectValveTree()
    {
        List<BaseValveType> valveTypeList = baseValveTypeMapper.selectList(new QueryWrapper<>());
        List<Ztree> ztrees = initZtree(valveTypeList);
        return ztrees;
    }

    /**
     * 对象转阀门树
     *
     * @param valveTypeList 阀门类型列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<BaseValveType> valveTypeList)
    {
        List<Ztree> ztrees = new ArrayList<Ztree>();
        for (BaseValveType baseValveType : valveTypeList)
        {
            BaseValveData baseValveData = new BaseValveData();
            baseValveData.setValveId(baseValveType.getTypeId().toString());
            baseValveData.setTypeId(baseValveType.getTypeId());
            baseValveData.setTypeName(baseValveType.getTypeName());

            Ztree ztree = new Ztree();
            ztree.setId(baseValveData.getValveId());
            ztree.setpId(baseValveData.getTypeId());
            ztree.setName(baseValveData.getTypeName());
            ztree.setTitle(baseValveData.getTypeName());
            ztrees.add(ztree);

            List<BaseValveData> valveList = baseValveDataMapper.selectList(new QueryWrapper<BaseValveData>().eq("type_id", baseValveType.getTypeId()));
            if(valveList!=null && valveList.size()>0){
                for (BaseValveData valveData : valveList){
                    ztree = new Ztree();
                    ztree.setId(valveData.getValveId());
                    ztree.setpId(valveData.getTypeId());
                    ztree.setName(valveData.getValveId());
                    ztree.setTitle(valveData.getValveId());
                    ztrees.add(ztree);
                }
            }
        }
        return ztrees;
    }
    /**
     * 根据条件分页查询已分配阀门列表
     *
     * @param valveData 阀门信息
     * @return 阀门信息集合信息
     */
    @Override

    public List<BaseValveData> selectAllocatedSubList(BaseValveData valveData)
    {
        return baseValveDataMapper.selectAllocatedSubList(valveData);
    }


    /**
     * 根据条件分页查询未分配阀门角色列表
     *
     * @param baseValveData 阀门信息
     * @return 阀门信息集合信息
     */
    @Override

    public List<BaseValveData> selectUnallocatedSubList(BaseValveData baseValveData)
    {
        return baseValveDataMapper.selectUnallocatedSubList(baseValveData);
    }

}
